package study.javaee.practice.config;

import org.springframework.context.annotation.Configuration;
import org.springframework.http.HttpMethod;
import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
import org.springframework.security.config.annotation.method.configuration.EnableGlobalMethodSecurity;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.builders.WebSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.web.context.SecurityContextPersistenceFilter;
import study.javaee.practice.filter.DataDecryptFilter;
import study.javaee.practice.handler.RestAuthenticationEntryPoint;
import study.javaee.practice.handler.RestfulAccessDeniedHandler;
import study.javaee.practice.service.UserService;

@Configuration
@EnableWebSecurity
@EnableGlobalMethodSecurity(prePostEnabled = true)
public class SecurityConfig extends WebSecurityConfigurerAdapter {
    final DataDecryptFilter dataDecryptFilter;
    final UserService userService;

    public SecurityConfig(DataDecryptFilter dataDecryptFilter, UserService userService) {
        this.dataDecryptFilter = dataDecryptFilter;
        this.userService = userService;
    }

    @Override
    protected void configure(HttpSecurity http) throws Exception {
        // 关闭跨站请求保护
        http.csrf().disable();
        // 允许options请求头
        http.authorizeRequests()
                .antMatchers(HttpMethod.OPTIONS)
                .permitAll();
        http.addFilterBefore(dataDecryptFilter, SecurityContextPersistenceFilter.class);
        // 添加权限禁止rest规范处理器
        http.exceptionHandling().accessDeniedHandler(new RestfulAccessDeniedHandler());
        // 添加未登录rest规范处理器
        http.exceptionHandling().authenticationEntryPoint(new RestAuthenticationEntryPoint());
    }

    @Override
    protected void configure(AuthenticationManagerBuilder auth) throws Exception {
        super.configure(auth);
        auth.userDetailsService(userService);
    }

    @Override
    public void configure(WebSecurity web) throws Exception {
        super.configure(web);
        web.ignoring().antMatchers("/static/**");
    }
}
